package com.xwj.controller.admin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonObject;
import com.xwj.Enums.StatusInfoEnum;
import com.xwj.config.FileUploadCosConfig;
import com.xwj.data.StaticData;
import com.xwj.dto.HouseInfoDto;
import com.xwj.entity.HouseInfoDetailEntity;
import com.xwj.entity.HouseInfoPhotosEntity;
import com.xwj.entity.PhotoDetail;
import com.xwj.entity.RaHourseInfo;
import com.xwj.service.Impl.RaHouseInfoServiceImpl;
import com.xwj.service.Impl.RaStatusInfoServiceImpl;
import com.xwj.service.holder.RaRegisterUserHolder;
import com.xwj.util.ValidatedUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;

@RestController
@RequestMapping("/admin/houseInfo/")
@Slf4j
public class HouseInfoController {

    @Autowired
    private RaStatusInfoServiceImpl raStatusInfoService;
    @Autowired
    private RaHouseInfoServiceImpl raHouseInfoService;
    @Autowired
    private FileUploadCosConfig fileUploadCos;

    @RequestMapping(value = "houseInfoList", method = RequestMethod.GET)
    public ModelAndView houseInfoList(ModelAndView modelAndView, int cloudId) {
        String label = StatusInfoEnum.HouseInfo.getName();
        modelAndView.addObject("cloudStatus", raStatusInfoService.findStatusByLabel(label));
        modelAndView.addObject("cloudId", cloudId);
        modelAndView.setViewName("/admin/houseInfo/houseInfo");
        return modelAndView;
    }

    /**
     * 显示或查找信息列表
     *
     * @param pageIndex
     * @param pageSize
     * @param cloudId
     * @return
     */
    @RequestMapping(value = "houseInfoDetail", method = {RequestMethod.POST, RequestMethod.GET})
    public Map<String, Object> houseInfoDetail(@RequestParam(value = "page") Integer pageIndex,
                                               @RequestParam(value = "limit") Integer pageSize,
                                               @RequestParam(value = "cloudId", required = false) Integer cloudId,
                                               @RequestParam(value = "key", required = false) String key) {
        PageInfo<RaHourseInfo> page;
        HouseInfoDto houseInfoDto = null;
        if (key != null) houseInfoDto = JSON.parseObject(key, new TypeReference<HouseInfoDto>() {
        });
        if (houseInfoDto == null)
            page = raHouseInfoService.findHouseInfoByCloudId(pageIndex, pageSize, cloudId);
        else
            page = raHouseInfoService.findByProperty(pageIndex, pageSize, houseInfoDto);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", page.getTotal());
        map.put("data", page.getList());
        return map;
    }


    @RequestMapping(value = "deleteById", method = RequestMethod.POST)
    public Map<String, Object> deleteById(@RequestParam("id") String id) {
        List<String> ids = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        ids.add(id);
        if (raHouseInfoService.deleteByIds(ids) > 0)
            map.put("msg", "删除成功");
        else
            map.put("msg", "数据操作异常");
        return map;
    }

    /**
     * 批量删除
     *
     * @param mydata
     * @return
     */
    @RequestMapping(value = "deleteBatchById", method = RequestMethod.POST)
    public Map<String, Object> deleteBatchById(@RequestParam(value = "mydata", required = false) String mydata) {
        Map<String, Object> map = new HashMap<>();
        List<RaHourseInfo> raHourseInfoList = JSON.parseArray(mydata, RaHourseInfo.class);
        if (raHourseInfoList.size() == 0) {
            map.put("msg", "未选中任何选项");
            return map;
        }
        List<String> ids = raHouseInfoService.parseListId(raHourseInfoList);
        if (raHouseInfoService.deleteByIds(ids) > 0)
            map.put("msg", "删除成功");
        else
            map.put("msg", "数据操作异常");
        return map;
    }

    @RequestMapping(value = "updateProperty", method = RequestMethod.POST)
    public Map<String, Object> updateProperty(HouseInfoDto houseInfoDto) {
        Map<String, Object> map = new HashMap<>();
        if (!RaRegisterUserHolder.hasUser(houseInfoDto.getUserId())) {
            map.put("msg", "没有该用户，请重新输入");
            return map;
        }
        if (!ValidatedUtils.checkCellphone(houseInfoDto.getPhone())) {
            map.put("msg", "请输入正确的联系电话");
            return map;
        }
        if (raHouseInfoService.updateProperty(houseInfoDto) > 0)
            map.put("msg", "更新成功");
        else
            map.put("msg", "数据操作异常");
        return map;
    }

    /**
     * 多照片上传
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "batch/upload", method = RequestMethod.POST)
    public Map<String, Object> handleFileUpload(HttpServletRequest request) {
        ServletContext context = request.getServletContext();
        String accountid = (String) context.getAttribute(StaticData.ADMIN_USER_LOGIN_ATTRIBUTE);
        Map<String, Object> map = new HashMap<>();
        String localPathDir = "/apartmentphoto";
        String localRealPathDir = request.getSession().getServletContext().getRealPath(localPathDir);
        File localSaveFile = new File(localRealPathDir);
        if (!localSaveFile.exists()) localSaveFile.mkdirs();
        String result = null;
        try {
            MultipartFile multipartFile = ((MultipartHttpServletRequest) request).getFile("file");
            String fileName = localRealPathDir + File.separator + multipartFile.getOriginalFilename();
            File file = new File(fileName);
            multipartFile.transferTo(file);
            result = fileUploadCos.uploadFile("/apartmentphoto/", fileName, multipartFile.getOriginalFilename());
            JSONObject jsonObject = JSON.parseObject(result);
            if (jsonObject.getInteger("code") == 0) {
                JsonObject jsonObject1 = new JsonObject();
                jsonObject1.addProperty("access_url", jsonObject.getJSONObject("data").getString("access_url"));
                jsonObject1.addProperty("name", multipartFile.getOriginalFilename());
                raHouseInfoService.accressUrlSet(jsonObject1.toString(), accountid + "_upload_house_picture");
            }

        } catch (IOException e) {
            log.error("后台用户{}多照片上传失败异常:", accountid, e);
            e.printStackTrace();
        }
        map.put("result", result);
        return map;
    }

    /**
     * 添加或更新
     *
     * @param userId
     * @param phone
     * @param cloudId
     * @param duiringTime
     * @param houseInfoDetailEntity
     * @param request
     * @return
     */
    @RequestMapping(value = "addOrUpdateHouseDetail", method = RequestMethod.POST)
    public Map<String, Object> addOrUpdateHouseDetail(@RequestParam(value = "userId", required = false) String userId,
                                                      @RequestParam(value = "phone", required = false) String phone,
                                                      @RequestParam(value = "cloudId", required = false) Integer cloudId,
                                                      @RequestParam(value = "duiringTime", required = false) Integer duiringTime,
                                                      @RequestParam(value = "id", required = false) String id,
                                                      HouseInfoDetailEntity houseInfoDetailEntity,
                                                      HttpServletRequest request) {
        ServletContext context = request.getServletContext();
        String accountid = (String) context.getAttribute(StaticData.ADMIN_USER_LOGIN_ATTRIBUTE);
        Set<Object> urlSet = raHouseInfoService.getAccressUrlSet(accountid + "_upload_house_picture");
        int index = 1;
        List<PhotoDetail> photoDetailList = new ArrayList<>();
        for (Object str : urlSet) {
            JSONObject jsonObject = JSON.parseObject((String) str);
            String url = jsonObject.getString("access_url");
            String name = jsonObject.getString("name");
            PhotoDetail photoDetail = new PhotoDetail(name, index, url, url);
            photoDetailList.add(photoDetail);
            index++;
        }
        Map<String, Object> map = new HashMap<>();
        HouseInfoPhotosEntity houseInfoPhotosEntity = new HouseInfoPhotosEntity();
        houseInfoPhotosEntity.setData(photoDetailList);
        houseInfoDetailEntity.setPhotos(houseInfoPhotosEntity);
        if (id == null) {
            if (!RaRegisterUserHolder.hasUser(userId)) {
                map.put("msg", "没有该用户，请重新输入");
                return map;
            }
            if (!ValidatedUtils.checkCellphone(phone)) {
                map.put("msg", "请输入正确的联系电话");
                return map;
            }
            if (houseInfoDetailEntity.getPhotos().getData().size() == 0) {
                map.put("msg", "图片未上传或长时间未保存已丢失，请上传图片");
                return map;
            }
            RaHourseInfo raHourseInfo = new RaHourseInfo(userId, phone, cloudId, duiringTime, JSON.toJSONString(houseInfoDetailEntity));
            if (raHouseInfoService.insertOneHouse(raHourseInfo) > 0) {
                raHouseInfoService.deleteSet(accountid + "_upload_house_picture");
                map.put("msg", "添加成功");
            } else
                map.put("msg", "添加失败");
        } else {
            Map<String, Object> data = new HashMap<>();
            RaHourseInfo raHourseInfo = raHouseInfoService.findHouseInfoById(id);
            if (raHourseInfo != null) {
                HouseInfoDetailEntity detailEntity =
                        JSON.parseObject(raHourseInfo.getDetailInfo(), new TypeReference<HouseInfoDetailEntity>() {
                        });
                if (houseInfoDetailEntity.getPhotos().getData().size() == 0) //若没上传图片则用原来的。否则覆盖原来的图片用最新的
                    houseInfoDetailEntity.getPhotos().setData(detailEntity.getPhotos().getData());
            }
            data.put("id", id);
            data.put("detailInfo", JSON.toJSONString(houseInfoDetailEntity));
            if (raHouseInfoService.updateDetail(data) > 0) {
                raHouseInfoService.deleteSet(accountid + "_upload_house_picture");
                map.put("msg", "更新成功");
            } else
                map.put("msg", "更新失败");
        }
        return map;
    }

}
